<template>
  <div class="container">
    <el-form ref="form" :model="form" label-width="80px" style="margin-top:20px;">
      <el-form-item label="测试封面">
        <el-upload
          ref="upload"
          action="http://localhost:8081/test/test/uploadCover"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :auto-upload="false"
          :on-success="uploadSuccess"
          :on-error="uploadError"
          :limit="limit"
        >
          <i class="el-icon-plus" />
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="标题">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="时间">
        <el-col :span="11">
          <el-time-picker
            v-model="form.date"
            placeholder="选择时间"
            style="width: 100%;"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-col>
      </el-form-item>
      <div v-for="(result, index) in form.resultList" :key="form.itemList.length + index" class="item">
        <el-form-item :label="index === 0 ? '设计分段' : ''">
          <el-input-number v-model="result.resultScore[0]" :disabled="true" />
          <el-input-number v-model="result.resultScore[1]" :disabled="true" />
          <el-input v-model="result.result" placeholder="请输入该分数段的结果" clearable />
          <div style="margin-top:20px">
            <el-button @click="handleResult(result)">删除</el-button>
            <el-button @click="editResult(result, index)">编辑</el-button>
          </div>
        </el-form-item>
      </div>
      <el-form-item>
        <el-button @click="addResult">添加分段</el-button>
      </el-form-item>
      <!-- 遍历已创建的选项渲染 -->
      <div v-for="(item, index) in form.itemList" :key="index" class="item">
        <el-form-item :label="(index+1)+''">
          <div class="item_title">
            <span>、{{ typeMap[item.type] }}: </span>
            <span v-text="item.title" />
          </div>
          <!-- 单项填空 -->
          <div v-if="item.type==='input'">
            <el-input class="disabled" placeholder="禁止输入" disabled />
          </div>
          <!-- 单选 -->
          <div v-else-if="item.type==='radio'">
            <div v-for="(elm, i) in item.textList" :key="i" class="warp">
              <el-radio :label="(i+1)+'、'" />
              <el-input v-model="item.textList[i]" style="width:900px" />
              分值：<el-input v-model="item.scoreList[i]" style="width:100px" />
            </div>
          </div>

          <!-- 多选 -->
          <div v-else-if="item.type==='checkbox'">
            <div v-for="(elm, i) in item.textList" :key="i" class="warp">
              <el-checkbox :label="(i+1)+'、'" />
              <el-input v-model="item.textList[i]" />
            </div>
          </div>

          <!-- 选择填空 -->
          <div v-else-if="item.type === 'select'">
            <el-select v-model="value" placeholder="请选择">
              <el-option
                v-for="(elm, i) in item.textList"
                :key="i"
                :label="item.textList[i]"
                :value="i+''"
              />
            </el-select>
          </div>

          <!-- 矩阵填空 -->
          <div v-else-if="item.type==='matrix'">
            <div v-for="(elm, i) in item.textList" :key="i" class="warp">
              <span> {{ item.textList[i] }}：</span>
              <el-input class="disabled" placeholder="禁止输入" disabled />
            </div>
          </div>
          <!-- 上移、下移、删除 -->
          <div style="margin-top: 10px">
            <el-button v-if="index!=0" @click="handleItem('up', item)">上移</el-button>
            <el-button v-if="index!=form.itemList.length-1" @click="handleItem('down', item)">下移</el-button>
            <el-button @click="handleItem('del', item)">删除</el-button>
            <el-button @click="edit(item, index)">编辑</el-button>
          </div>
        </el-form-item>
      </div>

      <!-- 添加选项 -->
      <el-form-item>
        <el-button @click="add('radio')">单选</el-button>
        <el-button @click="add('checkbox')">多选</el-button>
        <el-button @click="add('input')">单项填空</el-button>
        <el-button @click="add('select')">选择填空</el-button>
        <el-button @click="add('matrix')">矩阵填空</el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即创建</el-button>
      </el-form-item>

      <!-- 添加分段弹出框 -->
      <div class="additem">
        <el-dialog
          title="添加分段"
          :visible.sync="show"
          width="50%"
        >
          <el-form-item>
            <el-tooltip class="item" effect="dark" content="包含" placement="top-start">
              <el-input-number v-model="num2" />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="不包含" placement="top-start">
              <el-input-number v-model="num3" style="margin-left: 20px" />
            </el-tooltip>
            <el-input v-model="resultText" placeholder="请输入分段结果" style="margin-top:20px" />
          </el-form-item>
          <span slot="footer" class="dialog-footer">
            <el-button @click="clearResult">取 消</el-button>
            <el-button type="primary" @click="resultDetermine">确 定</el-button>
          </span>
        </el-dialog>
      </div>
      <!-- 添加选项弹出框 -->
      <div class="additem">
        <el-dialog
          :title="typeMap[questItem.type]"
          :visible.sync="showItem"
          width="50%"
        >
          <el-form-item label="标题">
            <el-input v-model="itemTitle" />
          </el-form-item>
          <el-form-item v-show="questItem.type != 'input'" label="添加选项">
            <el-input-number v-model="num" :min="1" :max="10" @change="handleChange" />
          </el-form-item>
          <el-form-item v-for="(text, i) in itemText" v-show="questItem.type != 'input'" :key="i" :label="'选项'+(i+1)">
            <el-input v-model="itemText[i]" />
          </el-form-item>
          <el-form-item v-for="(score, j) in scoreText" v-show="questItem.type != 'input'" :key="j+scoreText.length" :label="'选项'+(j+1)+'分值'">
            <el-input v-model="scoreText[j]" />
          </el-form-item>
          <span slot="footer" class="dialog-footer">
            <el-button @click="clearItem">取 消</el-button>
            <el-button type="primary" @click="determine">确 定</el-button>
          </span>
        </el-dialog>
      </div>
    </el-form>
  </div>
</template>
<script>
import { addTest } from '@/api/test'
import Swal from 'sweetalert2'
export default {
  data() {
    return {
      limit: 1,
      dialogImageUrl: '',
      dialogVisible: false,
      cover_url: '',
      value: '',
      matrixsNum: 1,
      num: 1,
      num1: 1,
      num2: 0,
      num3: 1,
      resultText: '',
      form: {
        itemList: [],
        name: '',
        date: '',
        resultList: []
      },
      itemTitle: '',
      itemText: new Array(1),
      scoreText: new Array(1),
      resultNumText: new Array(2),
      questItem: {},
      resultItem: {},
      showItem: false,
      show: false,
      typeMap: {
        radio: '单选',
        checkbox: '多选',
        input: '问答',
        matrix: '矩阵问答',
        select: '选择'
      },
      editIndex: '',
      editIndex2: ''
    }
  },
  watch: {
    showItem() {
      if (!this.showItem) {
        this.clearItem()
      }
    },
    show() {
      if (!this.show) {
        this.clearResult()
      }
    }
  },
  methods: {
    addResult() {
      this.show = true
    },
    // 创建选项
    add(type) {
      this.questItem.type = type
      this.showItem = true
    },
    // 增加/减少 子选项
    handleChange(val) {
      this.itemText.length = val
      this.scoreText.length = val
    },
    // 确定将选项添加进列表中进行渲染
    determine() {
      if (this.questItem.type === 'input') {
        // 填空
        if (this.itemTitle === '') {
          this.$message('请输入选项的标题内容')
          return
        }
        if (this.editIndex !== '') {
          this.questItem.title = this.itemTitle
          this.form.itemList.splice(this.editIndex, 1, this.questItem)
          this.editIndex = ''
        } else {
          this.questItem.title = this.itemTitle
          this.form.itemList.push(this.questItem)
        }
        this.clearItem()
      } else if (this.questItem.type === 'radio' || this.questItem.type === 'checkbox' || this.questItem.type === 'matrix' || this.questItem.type === 'select') {
        // 单选、多选、矩阵
        if (this.itemTitle === '') {
          this.$message('请输入选项的标题内容')
          return
        }
        for (var i = 0; i < this.itemText.length; i++) {
          if (this.itemText[i] === '' || this.itemText[i] === undefined) {
            this.$message('请完整输入每个选项内容')
            return
          }
        }
        for (var j = 0; j < this.scoreText.length; j++) {
          if (this.scoreText[j] === '' || this.scoreText[j] === undefined) {
            this.$message('请务必输入每个选项的分值')
            return
          }
        }
        if (this.editIndex !== '') {
          this.questItem.scoreList = this.scoreText
          this.questItem.title = this.itemTitle
          this.questItem.textList = this.itemText
          this.form.itemList.splice(this.editIndex, 1, this.questItem)
          this.editIndex = ''
        } else {
          this.questItem.scoreList = this.scoreText
          this.questItem.title = this.itemTitle
          this.questItem.textList = this.itemText
          this.form.itemList.push(this.questItem)
        }
        this.clearItem()
      }
    },
    resultDetermine() {
      if (this.resultText === '') {
        this.$message('请输入分段结果')
        return
      }
      if (this.editIndex2 !== '') {
        this.resultNumText[0] = this.num2
        this.resultNumText[1] = this.num3
        this.resultItem.resultScore = this.resultNumText
        this.resultItem.result = this.resultText
        this.form.resultList.splice(this.editIndex2, 1, this.resultItem)
        this.editIndex2 = ''
      } else {
        this.resultNumText[0] = this.num2
        this.resultNumText[1] = this.num3
        this.resultItem.resultScore = this.resultNumText
        this.resultItem.result = this.resultText
        this.form.resultList.push(this.resultItem)
      }
      this.clearResult()
    },
    // 编辑
    edit(item, editIndex) {
      this.editIndex = editIndex
      if (item.type !== 'input') {
        this.num = item.textList.length
        this.num1 = item.scoreList.length
        this.showItem = true
        this.questItem = item
        this.itemTitle = item.title
        this.itemText = []
        this.scoreText = []
        this.itemText.push(...item.textList)
        this.scoreText.push(...item.scoreList)
      } else {
        this.showItem = true
        this.questItem = item
        this.itemTitle = item.title
      }
    },
    editResult(result, editIndex) {
      this.editIndex2 = editIndex
      this.num2 = result.resultScore[0]
      this.num3 = result.resultScore[1]
      this.show = true
      this.resultItem = result
      this.resultText = result.result
    },
    // 关闭弹窗，清空数据
    clearItem() {
      this.num = 1
      this.num1 = 1
      this.itemTitle = ''
      this.itemText = ['']
      this.scoreText = ['']
      this.questItem = {}
      this.showItem = false
    },
    // 关闭分段弹框,清空数据
    clearResult() {
      this.num2 = 0
      this.num3 = 1
      this.resultNumText = ['']
      this.resultItem = {}
      this.resultText = ''
      this.show = false
    },
    // 判断上移、下移、删除
    handleItem(val, item) {
      switch (val) {
        case 'up':
          this.moveUp(item)
          break
        case 'down':
          this.moveDown(item)
          break
        case 'del':
          this.delItem(item)
          break
        default:
          throw new Error('该操作不存在！')
      }
    },
    // 上移
    moveUp(item) {
      const index = this.form.itemList.indexOf(item)
      this.form.itemList.splice(index, 1)
      this.form.itemList.splice(index - 1, 0, item)
    },
    // 下移
    moveDown(item) {
      const index = this.form.itemList.indexOf(item)
      this.moveUp(this.form.itemList[index + 1])
    },
    // 删除
    delItem(item) {
      const index = this.form.itemList.indexOf(item)
      this.form.itemList.splice(index, 1)
    },
    handleResult(result) {
      const index = this.form.resultList.indexOf(result)
      this.form.resultList.splice(index, 1)
    },
    // 提交
    onSubmit() {
      if (this.form.name === '') {
        this.$message('请输入标题内容')
        return
      }
      if (this.form.date === '' || this.form.date === null) {
        this.$message('请选择时间')
        return
      }
      if (this.form.itemList.length === 0) {
        this.$message('至少添加一个选项')
        return
      }
      console.log(this.form)
      this.$refs.upload.submit()
    },
    uploadSuccess(response, file, fileList) {
      addTest({ name: this.form.name, date: this.form.date, testSubjects: this.form.itemList, cover: response.data, resultList: this.form.resultList }).then(res => {
        Swal.fire({
          title: '测试卷创建成功',
          icon: 'success',
          confirmButtonText: 'OK',
          heightAuto: false
        })
        console.log(this.form)
        this.form = ''
        this.textList = ['']
        this.scoreList = ['']
      })
    },
    uploadError(response, file, fileList) {
      Swal.fire({
        title: '封面上传失败',
        icon: 'error',
        confirmButtonText: 'OK',
        heightAuto: false
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }
  }
}
</script>
<style lang="scss" scoped>
.warp{
  display: flex;
  align-items: center;
}
.disabled{
  background: #F5F7FA;
}
input{
  -webkit-appearance: none;
  background-color: #FFF;
  background-image: none;
  border-radius: 4px;
  border: 1px solid #DCDFE6;
  box-sizing: border-box;
  color: #606266;
  font-size: inherit;
  height: 40px;
  line-height: 40px;
  outline: 0;
  padding: 0 15px;
  transition: border-color .2s cubic-bezier(.645,.045,.355,1);
  margin: 10px 0 0;
}
.el-radio {
    color: #606266;
    cursor: pointer;
    margin-right: 0;
}
</style>
